package com.huamao.zh.service.impl;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.huamao.zh.constants.ScoreType;
import com.huamao.zh.mapper.AgentsApplysMapper;
import com.huamao.zh.mapper.DateMapper;
import com.huamao.zh.mapper.UsersUpgradeMapper;
import com.huamao.zh.model.Account;
import com.huamao.zh.model.AgentsApplys;
import com.huamao.zh.model.LogScore;
import com.huamao.zh.model.SKDate;
import com.huamao.zh.model.Users;
import com.huamao.zh.model.UsersUpgrade;
import com.huamao.zh.service.AccountService;
import com.huamao.zh.service.AgentsApplysService;
import com.huamao.zh.service.AgentsProbationService;
import com.huamao.zh.service.LogScoreFreezeService;
import com.huamao.zh.service.LogScoreService;
import com.huamao.zh.service.UsersService;

@Service
@Transactional
public class AgentsProbationServiceImpl implements AgentsProbationService {

	@Autowired
	private AgentsApplysService agentsApplysService;

	@Autowired
	private LogScoreFreezeService logScoreFreezeService;

	@Autowired
	private LogScoreService logScoreService;

	@Autowired
	private AccountService accountService;

	@Autowired
	private UsersService usersService;

	@Autowired
	private DateMapper dateMapper;

	@Autowired
	private UsersUpgradeMapper usersUpgradeMapper;
	@Autowired
	private AgentsApplysMapper agentsApplysMapper;

	public final static int UNBAT = 1;
	public final static int BATING = 9;
	public final static int BATED = 2;

	/**
	 * 股东试用期处理
	 */
	public void dealAgents() throws Exception {
		// LogUtil.info(LogCodeType.CODE_7001, "======股东试用期处理======");
		synchronized (this.getClass()) {
			Map<String, Object> agentsMap = new HashMap<String, Object>();
			agentsMap.put("batFlag", UNBAT);
			int listCount = agentsApplysService.queryListCount(agentsMap);
			// LogUtil.info(LogCodeType.CODE_7001, "======查出所有需要处理的股东======" +
			// listCount);

			// 处理前更新dealFlag，需改动mapper
			agentsMap.put("batTarget", BATING);
			agentsMap.put("batFrom", UNBAT);
			agentsApplysService.updateDealFlag(agentsMap);

			for (Integer i = 0; i < listCount; i += 500) {
				agentsMap.put("batFlag", BATING);
				agentsMap.put("start", i);
				agentsMap.put("offset", 500);
				System.out.println(agentsMap.get("batFlag") + "==============================================");
				List<AgentsApplys> agentsList = agentsApplysService.queryListByBatFlag(agentsMap);

				for (AgentsApplys agent : agentsList) {
					// 处理agent
					dealAgentMain(agent);
				}
			}

			agentsMap.clear();
			agentsMap.put("batTarget", BATED);
			agentsMap.put("batFrom", BATING);
			agentsMap.put("batTime", new Date());
			agentsApplysService.updateDealFlag(agentsMap);
		}
	}

	/**
	 * 处理agent主流程，可提供接口
	 */
	public void dealAgentMain(AgentsApplys agent) throws Exception {
		// LogUtil.info(LogCodeType.CODE_7001, "======进入主流程======" +
		// agent.getShaId());
		Account account = accountService.getByUserId(agent.getUserId());
		Users user = usersService.getByUserId(agent.getUserId());

		// 上线的id
		int inviteId = user.getInviteId();
		// LogUtil.info(LogCodeType.CODE_7001, "======inviteId======" + inviteId
		// + "====userId===" + user.getUserId());
		// 上线用户信息
		Users upLevel = usersService.getOneByInviteId(inviteId);
		if (upLevel == null) {
			// LogUtil.info(LogCodeType.CODE_7001, "======上线不存在，跳过======");
			return;
		}
		// 判断上线升级经理时间是否小于二审通过时间+7个工作日
		Date finalCheckdate = sevenWorkingDaysBefore(agent.getTwoCheckTime());
		if (upLevel.getUserType() == 2 && upLevel.getIsAgent() == 0) {
			// LogUtil.info(LogCodeType.CODE_7001, "======上线是经理======");
			UsersUpgrade upgrade = usersUpgradeMapper.getByUserId(inviteId);
			if (upgrade == null) {
				return;
			}
			Date upgradeTime = upgrade.getUpgradeTime();
			if (finalCheckdate.before(upgradeTime)) {
				return;
			}
		} else if (upLevel.getUserType() < 2 && upLevel.getIsAgent() > 0) {
			// LogUtil.info(LogCodeType.CODE_7001, "======上线是股东======");
			AgentsApplys agentsApplys = agentsApplysMapper.getByUserId(inviteId);
			if (agentsApplys == null) {
				return;
			}
			Date twoCheckTime = agentsApplys.getTwoCheckTime();
			if (finalCheckdate.before(twoCheckTime)) {
				return;
			}
		} else if (upLevel.getUserType() == 2 && upLevel.getIsAgent() > 0) {
			// LogUtil.info(LogCodeType.CODE_7001, "======上线既是经理又是股东======");
			UsersUpgrade upgrade = usersUpgradeMapper.getByUserId(inviteId);
			AgentsApplys agentsApplys = agentsApplysMapper.getByUserId(inviteId);
			if (upgrade == null || agentsApplys == null) {
				return;
			}
			Date upgradeTime = upgrade.getUpgradeTime();
			Date twoCheckTime = agentsApplys.getTwoCheckTime();
			if (upgradeTime.before(twoCheckTime) && finalCheckdate.before(upgradeTime)) {
				return;
			}
			if (twoCheckTime.before(upgradeTime) && finalCheckdate.before(twoCheckTime)) {
				return;
			}
		} else {
			// LogUtil.info(LogCodeType.CODE_7001,
			// "======上线不是经理，也不是股东，跳过======");
			return;
		}
		BigDecimal moneyScore = agent.getMoney().multiply(new BigDecimal(200));
		// 查出上级，发积分
		Account accountUp = accountService.getByUserId(inviteId);
		BigDecimal preScore = accountUp.getTotalScore();
		// LogUtil.info(LogCodeType.CODE_7001, "======prescore======" +
		// preScore);

		accountUp.setScore(moneyScore);
		accountUp.setTotalScore(moneyScore);
		try {
			accountService.updateProbationScore(accountUp);
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		// 记日志
		addScoreData(user.getUserId(), inviteId, moneyScore, preScore, agent.getOrderNo());
	}

	public Date sevenWorkingDaysBefore(Date date) throws Exception {

		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		int sevenWorkingDays = 0;

		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
		String DateFormat = simpleDateFormat.format(calendar.getTime());

		List<SKDate> skDates = dateMapper.queryList(null);
		SKDate skDate = null;
		for (SKDate SKDate : skDates) {
			if (DateFormat.equals(SKDate.getDate().toString())) {
				skDate = SKDate;
			}
		}

		List<SKDate> SkDatesChliden = skDates.subList(skDates.indexOf(skDate), skDates.size());

		for (SKDate skDateChliden : SkDatesChliden) {
			if (skDateChliden.getStatus() == 0) {
				sevenWorkingDays = sevenWorkingDays + 1;
			}
			if (sevenWorkingDays == 7) {
				skDate = skDateChliden;
				break;
			}
		}

		List<SKDate> SkDatesList = SkDatesChliden.subList(SkDatesChliden.indexOf(skDate), SkDatesChliden.size());

		skDate = SkDatesList.get(0);
		String stringDate = skDate.getDate().toString();
		String year = stringDate.substring(0, 4);
		String month = stringDate.substring(4, 6);
		String day = stringDate.substring(6, 8);

		SimpleDateFormat simpleDate = new SimpleDateFormat("yyyy-MM-dd");
		Date sevenWorkingDate = simpleDate.parse(year + "-" + month + "-" + day);

		return sevenWorkingDate;

	}

	/**
	 * @param fromId
	 * @param userId
	 * @param getScore
	 * @param preScore
	 * @param orderNo
	 */
	private void addScoreData(Integer fromId, Integer userId, BigDecimal getScore, BigDecimal preScore,
			String orderNo) {
		LogScore logScoreObj = new LogScore();
		logScoreObj.setType(ScoreType.Subordinate_upgrade_agent.getCode());
		logScoreObj.setFromId(fromId);
		logScoreObj.setUserId(userId);
		logScoreObj.setOrderNo(orderNo);
		logScoreObj.setPreScore(preScore);
		logScoreObj.setScoreType(1);
		logScoreObj.setScore(getScore);
		logScoreObj.setRemark(ScoreType.Subordinate_upgrade_agent.getName());
		logScoreObj.setDataFlag(1);
		logScoreObj.setCreateTime(new Date());
		try {

			// LogUtil.info(LogCodeType.CODE_7001, "新增日志");
			logScoreService.add(logScoreObj);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}